<?php

namespace App\Http\Controllers\Api;

use App\Comment;
use App\Http\Controllers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Order;
use App\OrderDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class CommentController extends Controller
{
    use ApiResponse;

    public $uid;

    public function __construct()
    {
        $this->uid = auth('api')->id();
    }

    public function index(Request $request)
    {
       $goods_id=$request->get('goods_id');
       $total_comment=0;
       $avg=0;
       if (Redis::scard("goods_comment:".$goods_id)>0){
           $list=Redis::smembers("goods_comment:".$goods_id);
           $list=collect($list);
           $total_comment=$list->count();
           $three_star_list=$list->filter(function ($item){

                   return $item>=3;

           });
           $three_star=$three_star_list->count();
           if ($total_comment>0){
               $avg=$three_star/$total_comment;
           }
       }else{
           $comments=Comment::where('goods_id',$goods_id)->where('parent_id',0)->pluck("star");
           $total_comment=$comments->count();
           $three_star_list=$comments->filter(function ($item){
                   return $item>=3;
           });
           $three_star=$three_star_list->count();

           if ($total_comment>0){
               $avg=$three_star/$total_comment;
           }

       }

       $paginate=Comment::with(['user','reply'])->where('goods_id',$goods_id)->where('parent_id',0)->paginate($request->get('size',10));
       $data=[
           'comment_total'=>$total_comment,
           'nice_comment'=>($avg*100)."%",
           'list'=>$paginate
       ];
       return $this->data($data);
    }

    public function store(Request $request)
    {

        $order = Order::where('order_number', $request->get('order_number'))->first();
        $goods_comment = $request->get('goods_comment');
        foreach ($goods_comment as $key => $value) {
            $data = [
                'comment' => $value['comment'],
                'uid' => $this->uid,
                'parent_id' => 0,
                'goods_id' => $value['goods_id'],
                'sku_id' => $value['sku_id'] ?? null,
                'sku' => $value['sku'] ?? "",
                'order_number' => $request->get('order_number'),
                'star' => $value['star'],
                'pictures' => $value['pictures'],
            ];
            $created = Comment::create($data);
        }

        $order->express_eva = $request->get('express_eva');
        $order->all_eva = $request->get('all_eva');
        $order->status = 2;
        $order->save();
        if ($created) {
            return $this->message_success("创建成功");
        } else {
            return $this->message_error("创建失败");
        }
    }
}
